//
//  SimpleNetWork.swift
//  SimpleNetWork
//
//  Created by mac on 15/3/2.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

///  请求的回调 closure
///
///  @param AnyObject? 请求结果
///  @param NSError?   错误信息
///
public typealias Complete = ( result: AnyObject?, error: NSError?)-> ()

extension SimpleNetWork {
    
    ///  根据多个 urls 来下载多张图片
    ///
    ///  :param: urls     图片的urls
    ///  :param: complete 完成的回调
    public func downImagesWithURLs(urls: [String], complete: Complete) {
        
    }
    
}

public class SimpleNetWork {
    private static let instance = SimpleNetWork()
    private static let DOMAIN_STR = "com.gpr.SimpleNetWork"
    var timeOut: NSTimeInterval = 15
    
    // MARK: 图片缓存路径
    var cachePath: String! = {
        let docPath: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String
        println("\(docPath)")
        return ""
    }()
    
    lazy var session: NSURLSession! = {
        return NSURLSession.sharedSession()
    }()
    
    
    /// 单例构造方法
    public class var shareInstance: SimpleNetWork {
        return instance
    }
    
    ///  请求一段JSON数据
    ///
    ///  :param: urlString 请求地址字符串
    ///  :param: method    请求方法类型
    ///  :param: params    请求的参数
    ///  :param: complete  请求完成的回调
    public func requestJSON(var urlString: String, _ method: HTTPMethod, _ params: [String: String]?, _ complete: Complete?){
        // 解析参数
        let paramString = self.queryString(params)
        if paramString == nil && method == HTTPMethod.POST{
            let error = NSError(domain: SimpleNetWork.DOMAIN_STR, code: 0, userInfo: ["请求方法" : "请求参数为空但请求方法为POST"])
            self.completeOperation(complete, error,nil)
            return
        }
        let request = self.requestFromURLString(urlString ,method, paramString)
        if request == nil {
            let error = NSError(domain: SimpleNetWork.DOMAIN_STR, code: 0, userInfo: ["请求方法: \(method) 或者 请求参数\(params) 有误" : "请检查"])
            self.completeOperation(complete, error,nil)
            return
        }
        session.dataTaskWithRequest(request!, completionHandler: { (resultData, _, error) -> Void in
            if error != nil {
                self.completeOperation(complete, error,nil)
            }
            // 反序列化
            let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(resultData, options: NSJSONReadingOptions.allZeros, error: nil)
            if json == nil {
                let error = NSError(domain: SimpleNetWork.DOMAIN_STR, code: 0, userInfo: ["error": "JSON反序列化失败"])
                self.completeOperation(complete, error,nil)
            } else {
                self.completeOperation(complete, nil,json)
            }
        }).resume()
    }
    
    ///  处理完成之后的操作
    ///
    ///  :param: complete 完成之后的操作 block
    ///  :param: error    操作的错误信息
    ///  :param: result   结果数据
    func completeOperation(complete: Complete? ,_ error: NSError?, _ result: AnyObject?) {
        if complete != nil {
            if complete == nil { return }
            if NSThread.currentThread().isMainThread {
                complete!(result: result, error: error)
            } else {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    complete!(result: result, error: error)
                })
            }
        }
        
    }
    
    ///  根据传进来的参数获得 NSURLRequest 对象
    ///
    ///  :param: urlString   参数地址字符串
    ///  :param: method      请求方式
    ///  :param: paramString 请求参数字符串
    ///
    ///  :returns: 请求
    func requestFromURLString(var urlString : String, _ method: HTTPMethod, _ paramString: String?) -> NSURLRequest?{
        if ( urlString.isEmpty || method.rawValue.isEmpty) {
            return nil
        }
        var request: NSMutableURLRequest? = nil
        if method == .GET {
            // 设置参数
            if paramString != nil {
                urlString = urlString + "?" + paramString!
            }
            request = NSMutableURLRequest(URL: NSURL(string: urlString)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeOut)
        } else if method == .POST {
            request = NSMutableURLRequest(URL: NSURL(string: urlString)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeOut)
            request?.HTTPMethod = method.rawValue
            // 设置参数
            request?.HTTPBody = paramString?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        }
        return request
    }
    
    ///  根据传进来的参数字典获得参数字符串
    ///
    ///  :param: params 参数字典
    ///
    ///  :returns: 参数字符串
    func queryString(params: [String: String]?) -> String? {
        if params == nil { return nil }
        var result = [String]()
        for (k,v) in params! {
            let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            result.append(str)
        }
        return join("&", result)
    }
    
}

public enum HTTPMethod : String {
    case GET = "GET"
    case POST = "POST"
}
